# -*- coding: utf-8 -*- 
from django.http import Http404 # wyjątek do podnoszenia jak mam zły dzi
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.http import HttpResponse #potrzebny żeby ręcznie zrobić responsa do popupów
from django.utils.encoding import force_unicode #potrzebny żeby javascript nie krzyczał
from django.core.paginator import ObjectPaginator, InvalidPage
#from intraorg.slowniki.models import *
from django import newforms as forms
from django.newforms import form_for_model
from pprint import pprint

@login_required
def slowniki(request, id='bank'):
    request.session['prev']=request.path
    list = []
    
    if id=='bank':
        paginate_by = 6
        for kraj in Bank.objects.all().order_by('kraj').values('kraj').distinct():
            list.extend(Bank.objects.filter(kraj=kraj['kraj']))

    elif id=='kraj':
        paginate_by = 15
        list = Kraj.objects.all()
    elif id=='miasto':
        paginate_by = 10
        for kraj in Miasto.objects.all().order_by('kraj').values('kraj').distinct():
            list.extend(Miasto.objects.filter(kraj=kraj['kraj']))

    paginator = ObjectPaginator(list, paginate_by)
    try:
        page = int(request.GET.get('page', '1'))
        collection = paginator.get_page(page - 1)
    except InvalidPage: 
        raise Http404

    return render_to_response('slowniki/slowniki.html', {'session':request.session,
        'list': collection,
        'paginate_by': paginate_by,
        'paginator':paginator,
        'page':page,
        'link':request.path,
        'id':id})

@login_required
def details(request, cat_id=False, object_id=False):
    request.session['prev']=request.path
    try:
        if cat_id=='bank':
            obj = Bank.objects.get(id=object_id)
        if cat_id=='miasto':
            obj = Miasto.objects.get(id=object_id)
        if cat_id=='kraj':
            obj = Kraj.objects.get(id=object_id)
    except:
        raise Http404
    return render_to_response('slowniki/%s_detail.html' % (cat_id), { \
        'session':request.session, \
        'obj':obj})
        
@login_required
def bank_new(request):
    request.session['prev']=request.path
    BankForm = form_for_model(Bank)
    dodany = False
    if request.method == 'POST':
        form = BankForm (request.POST)
        if form.is_valid():
            try:
                form.save()
            except:
                pass
        dodany = True
    else:
        form = BankForm (auto_id=True)
    return render_to_response('slowniki/bank_new.html', {'form':form, 'session':request.session, 'dodany':dodany})

@login_required
def kraj_new(request):
    request.session['prev']=request.path
    KrajForm = form_for_model(Kraj)
    dodany = False
    if request.method == 'POST':
        form = KrajForm (request.POST)
        if form.is_valid():
            try:
                form.save()
            except:
                pass
        dodany = True
    else:
        form = KrajForm (auto_id=True)
    return render_to_response('slowniki/kraj_new.html', {'form':form, 'session':request.session, 'dodany':dodany})

@login_required
def miasto_new(request):
    request.session['prev']=request.path
    MiastoForm = form_for_model(Miasto)
    dodany = False
    if request.method == 'POST':
        form = MiastoForm (request.POST)
        if form.is_valid():
            try:
                form.save()
            except:
                pass
        dodany = True
    else:
        form = MiastoForm (auto_id=True)
    return render_to_response('slowniki/miasto_new.html', {'form':form, 'session':request.session, 'dodany':dodany})

"""
POPUPY do wszystkich modeli
"""
@login_required
def nowy_element_popup(request, type=None):
    if type=="miasto":
        MiastoForm = form_for_model(Miasto)
        if request.method == 'POST':
            form = MiastoForm (request.POST)
        else:
            form = MiastoForm (auto_id='id_%s')
    elif type=="kraj":
        KrajForm = form_for_model(Kraj)
        if request.method == 'POST':
            form = KrajForm (request.POST)
        else:
            form = KrajForm (auto_id='id_%s')
    elif type=="bank":
        BankForm = form_for_model(Bank)
        if request.method == 'POST':
            form = BankForm (request.POST)
        else:
            form = BankForm (auto_id='id_%s')
    else:
        raise Http404
    if request.method == 'POST':
        if form.is_valid():
            if type=="miasto":
                try:
                    obj = Miasto.objects.create(
                        nazwa=form.cleaned_data['nazwa'],
                        kraj=form.cleaned_data['kraj'],)
                except:
                    return render_to_response('slowniki/%s_new_popup.html' % type, \
                        {'form':form, 'session':request.session, 'exists':True})
                    
            elif type=="kraj":
                try:
                    obj = Kraj.objects.create(
                        nazwapl=form.cleaned_data['nazwapl'],
                        nazwahol=form.cleaned_data['nazwahol'],
                        nazwade=form.cleaned_data['nazwade'],
                        kodkraju=form.cleaned_data['kodkraju'],)
                except:
                    return render_to_response('slowniki/%s_new_popup.html' % type, \
                        {'form':form, 'session':request.session, 'exists':True})
            elif type=="bank":
                try:
                    obj = Bank.objects.create(
                        nazwa=form.cleaned_data['nazwa'],
                        kraj=form.cleaned_data['kraj'],
                        bic_swift=form.cleaned_data['bic_swift'],)
                except:
                    return render_to_response('slowniki/%s_new_popup.html' % type, \
                        {'form':form, 'session':request.session, 'exists':True})            
            pk_value = obj._get_pk_val()
            #if type(pk_value) is str:                           
            #    pk_value = '"%s"' % pk_value.replace('"', '\\"')  
            return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, %s, "%s");</script>' % (pk_value, force_unicode(obj).replace('"', '\\"')))  
    return render_to_response('slowniki/%s_new_popup.html' % type, \
        {'form':form, 'session':request.session})
